<template>
  <entity-view
    :operator-type="operatorType"
    :model="beanInfo"
    @submit="submit"
    :rules="rules"
    ref="form"
  >
    <div class="sub-content-flex">
      <form-item
        label="机构标识"
        v-model="beanInfo.instId"
        prop="instId"
        disabled
      >
      </form-item>
      <form-item
        label="渠道标识"
        v-model="beanInfo.srcChannelId"
        prop="srcChannelId"
      >
      </form-item>
      <form-item
        label="渠道名称"
        v-model="beanInfo.srcChannelName"
        prop="srcChannelName"
      ></form-item>
      <form-item
        label="渠道状态"
        inputType="select"
        :options="transChannelStatusList"
        v-model="beanInfo.transChannelStatus"
        prop="transChannelStatus"
        @change="(value) => handleChange(value, 'transChannelStatus')"
      ></form-item>
      <form-item
        label="业务控制规则"
        inputType="select"
        :options="bizCtrlRuleList"
        v-model="beanInfo.bizCtrlRule"
        prop="bizCtrlRule"
        @change="(value) => handleChange(value, 'transChannelStatus')"
      ></form-item>
      <form-item
        label="营业开始时间"
        v-model="beanInfo.bizStartTime"
        prop="bizStartTime"
      ></form-item>
      <form-item
        label="营业截止时间"
        v-model="beanInfo.bizEndTime"
        prop="bizEndTime"
      ></form-item>
      <form-item
        style="width: 100%"
        label="支持账户类型"
        inputType="checkbox"
        v-model="supportAcctType"
        prop="supportAcctType"
        :options="supportAcctTypeList"
        @change="supportAcctTypeChange"
      >
        <a-checkbox
          class="checkAll"
          :checked="checkAll"
          @change="onCheckAllChange"
        >全选</a-checkbox
        >
        <a-checkbox-group
          class="check-box-group"
          v-model="supportAcctTypeChecked"
          :options="supportAcctTypeList"
          :disabled="operatorType === 'view' || operatorType === 'delete'"
          @change="supportAcctTypeChange"
        >
        </a-checkbox-group>
      </form-item>
      <form-item
        style="width: 100%"
        label="支持交易配置"
        inputType="transfer"
        :data-source="surportTxnList"
        show-search
        :filter-option="filterOption"
        :target-keys="targetKeys"
        :render="(item) => item.title"
        @change="surportTxnListChange"
        @search="handleSearch"
      ></form-item>
      <form-item
        label="停用原因"
        v-model="beanInfo.stopReason"
        prop="stopReason"
        inputType="textarea"
        v-if="operatorType != 'update' && beanInfo.transChannelStatus!='Y'"
      ></form-item>
    </div>
    <div href="">
      <button @click="goItem" v-if="operatorType === 'edit'" >
        交易信息配置管理
      </button>
      <a-modal>
        <p-txn-cfg/>
      </a-modal>
    </div>
  </entity-view>
</template>
<script>
  import EntityView from "../../../../components/common/entityView/EntityView.vue";
  import FormItem from "../../../../components/common/entityView/FormItem.vue";
  import PTxnCfg from "../pTxnCfg/PTxnCfg.vue";


  export default {
    name: "PSrcChannelOperation",
    components: {
      EntityView,
      FormItem,
      PTxnCfg,
    },
    props: {
      query: Object,
    },
    data: function () {
      return {
        URL: "/igas/pTxnCfg",
        modalVisible: false,
        modalTitle: "",
        operatorType: "edit",
        beanInfo: {
          baseProdCode: "",
          prodName: "",
          prodDesc: "",
        },
        rules: {
          instId: [{ required: true, message: "必填", trigger: "blur" }],
          srcChannelId: [{ required: true, message: "必填", trigger: "blur" }],
          wctSecName: [{ required: true, message: "必填", trigger: "blur" }],
          stopReason: [{ required: true, message: "必填", trigger: "blur" }],
        },
        transChannelStatusList: [
          { value: "Y", name: "启用" },
          { value: "N", name: "停用" },
        ],
        bizCtrlRuleList: [
          { value: "0", name: "按自然日" },
          { value: "1", name: "按工作日" },
        ],
        supportAcctType: [],
        supportAcctTypeList: [],
        supportAcctTypeChecked: [],
        targetKeys: [],
        selectOptions: [],
        loading: false,
        pageInfo: {},
        surportTxnList: [],
        indeterminate: true,
        checkAll: false,
      };
    },
    methods: {
      filterOption(inputValue, option) {
        return option.title.indexOf(inputValue) > -1;
      },
      goItem() {
        this.$emit("closeModal");
        this.$router.push(this.URL);
      },
      handleChange(value, param) {
        this.beanInfo[param] = value;
      },
      async getEditData(beanInfo) {
        const params = {
          instId: beanInfo.instId,
          srcChannelId: beanInfo.srcChannelId,
          transChannelId: beanInfo.transChannelId,
          optFlag: this.operatorType,
        };
        const res = await this.$get("/admin/igas/pSrcChannelInfo/edit", params);
        if (res.status === 200) {
          this.supportAcctTypeList = res.data.accTypes.filter((i) => {
            return i.value !== "*";
          });
          let obj = res.data.allTxn;
          let arr = Object.entries(obj).map((item) => {
            return {
              key: item[0],
              title: item[1],
              chosen: false,
            };
          });
          this.surportTxnList = arr;
          this.beanInfo = res.data.entity;
          this.targetKeys = res.data.entity.surportTxnList;
          this.beanInfo.bizCtrlRule = this.beanInfo.bizCtrlRule.split(",");
          if (this.beanInfo.supportAcctType=="*"){
            this.checkAll = true;
            this.supportAcctTypeChecked = this.beanInfo.supportAcctTypeList;
          }else {
            this.supportAcctTypeChecked = this.beanInfo.supportAcctTypeList;
          }
          return true;
        } else {
          this.loading = false;
          this.$message.error(res.data.message);
          return false;
        }
      },
      async openModal(type = "view", beanInfo) {
        if (typeof type !== "string") {
          return;
        }
        this.resetFields();
        this.$store.commit("setting/setFullscreenLoading", true);
        const modalName = "交易渠道";
        this.modalTitle = { edit: `编辑${modalName}`, view: `${modalName}详情` }[
          type
          ];
        this.$store.commit("setting/setFullscreenLoading", false);
        this.operatorType = type;
        if (type === "edit" || type === "view") {
          this.setBeanInfo(beanInfo);
        }
      },
      async submit() {
        let res;
        switch (this.operatorType) {
          case "edit":
            res = await this.edit();
            break;
          case "cancel":
            res = await this.edit();
            break;
          case "view":
            res = true;
            break;
          default:
            break;
        }
        return res;
      },
      async edit() {
        const res = await this.$refs.form.validate();
        if (res) {
          const surportTxnList = [];
          this.targetKeys.map((i) => {
            surportTxnList.push(i);
          });
          const params = {};

          this.beanInfo.surportTxnList = surportTxnList
          this.beanInfo.bizCtrlRule = this.beanInfo.bizCtrlRule.join(",");
          this.beanInfo.supportAcctType = this.operatorType==='cancel'?this.beanInfo.supportAcctType : this.supportAcctTypeChecked.join(",");
          const optFlag =
            this.operatorType === "edit"
              ? "upd"
              : this.beanInfo.transChannelStatus === "Y"
              ? "stop"
              : "use";
          this.beanInfo.stopReason =
            optFlag === "use" ? "" : this.beanInfo.stopReason;
          Object.assign(params, this.beanInfo, {
            optFlag,
          });
          console.log(params);
          const res = await this.$put(
            "/admin/igas/pSrcChannelInfo/update",
            params
          );
          if (res.status === 200) {
            this.$message.success("保存成功！");
            return true;
          } else {
            this.$message.error(res.data.message);
            return false;
          }
        }
      },
      resetFields() {
        return this.$refs.form && this.$refs.form.resetFields();
      },
      setOperatorType(type) {
        this.operatorType = type;
      },
      async setBeanInfo(beanInfo) {
        this.beanInfo = beanInfo;
        await this.getEditData(beanInfo);

        //初始化 复选框
        // const supportAcctType = this.beanInfo.supportAcctType;
        // const supportAcctTypeChecked = [];
        // console.log(supportAcctType)
        // supportAcctType.forEach((i, index) => {
        //   this.supportAcctTypeList.forEach((j, _index) => {
        //     if (i === "Y" && index === _index) {
        //       supportAcctTypeChecked.push(j.value);
        //     }
        //   });
        // });
        // this.supportAcctTypeChecked = supportAcctTypeChecked;
        // this.checkAll = supportAcctType.indexOf("*") > -1 ? true : false;
        // console.log(this.supportAcctTypeChecked);
        // console.log(this.checkAll);
       },
      async getOne() {
        try {
          const res = await this.$get("/admin/igas/pSrcChannelInfo/getOne", {
            srcChannelId: this.beanInfo.srcChannelId,
            instId: this.beanInfo.instId,
            transChannelId: this.beanInfo.transChannelId,
          });

          this.beanInfo = res.data || {};
          this.beanInfo.bizCtrlRule = this.beanInfo.bizCtrlRule.split(",");
          this.beanInfo.supportAcctType = this.beanInfo.supportAcctType.split("");
          this.supportAcctTypeChecked=this.beanInfo.supportAcctTypeList;
        } catch (e) {
          console.error(e);
        }
      },
      supportAcctTypeChange(value) {
        this.indeterminate = !!value.length && value.length < this.supportAcctTypeList.length;
        this.checkAll = value.length === this.supportAcctTypeList.length;
      },
      onCheckAllChange(e) {
        //   Object.assign(this, {
        //       supportAcctTypeChecked: e.target.checked ? ["*"] : [],
        //       indeterminate: false,
        //       checkAll: e.target.checked,
        //       indetermlinate: false,
        //       checkAl: e.target.checked,
        // });
        if (this.checkAll == true){
          this.supportAcctTypeChecked = [];
          this.checkAll = false;
        }else {
          for (var i in this.supportAcctTypeList){
            var supportAcctTypeData =  this.supportAcctTypeList[i].value;
            var type = true;
            for (var j in  this.supportAcctTypeChecked){
              if ( supportAcctTypeData == this.supportAcctTypeChecked[j]){
                type = false;
                break;
              }
            }
            if (type){
              this.supportAcctTypeChecked.push(supportAcctTypeData)
            }
          }
          this.checkAll = true;
        }




      },
      surportTxnListChange(targetKeys, direction, moveKeys) {
        console.log(targetKeys, direction, moveKeys);
        this.targetKeys = targetKeys;
      },
      handleSearch(dir, value) {
        console.log("search:", dir, value);
      },
    },
  };
</script>

<style scoped>
  .subtitle {
    width: 100%;
    font-size: 18px;
    margin-bottom: 10px;
  }
  .sub-content-flex {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  .sub-content-block {
    display: block;
    flex-wrap: wrap;
    width: 100%;
  }
  .checkAll {
    display: block;
    line-height: unset;
  }
</style>
